<template>
  <div class="chartarea">
    <div v-if="isboard" class="title">
      <h1>{{ chartTitle }}</h1>
      <!-- <p>{{ dateStr }}</p> -->
    </div>
    <div class="tools">
      <div class="timepicker" v-if="timepicker">
        <el-date-picker
          v-if="pickerType == 'week'"
          v-model="weekDate"
          type="week"
          format="yyyy 第 WW 周"
          placeholder="选择周"
          @change="timeChange"
        ></el-date-picker>
        <el-date-picker
          v-else
          v-model="date"
          :type="pickerType"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="timeChange"
        ></el-date-picker>

        <!--  -->
      </div>
      <div class="toolbox" v-if="toolbox">
        <div class="download" @click="downLoadHandle">下载数据</div>
        <div class="chart_type">
          <span>图标类型:</span>
          <div class="type_box">
            <i
              :class="{ 
                    'iconfont':true,
                    'icon-zhexiantu':true,
                    'active':chartType == 'line'?true:false }"
              @click="checkChartType('line')"
            ></i>
            <i
              :class="{ 
                    'iconfont':true,
                    'icon-zhuzhuangtu':true,
                    'active':chartType == 'bar'?true:false }"
              @click="checkChartType('bar')"
            ></i>
            <i
              :class="{ 
                    'iconfont':true,
                    'icon-hengxiangzhuzhuangtu':true,
                    'active':chartType == 'hbar'?true:false }"
              @click="checkChartType('hbar')"
            ></i>
          </div>
        </div>
      </div>
    </div>
    <div v-if="isboard" ref="canvas_box"></div>
    <div v-else class="canvas_box" ref="canvas_box"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { drawnLine, drawnBar, drawnHBar } from "../utils/chart";
import { base64ToBlob } from "../utils/processImg";
export default {
  name: "ChartArea",
  props: {
    // 看板页展示title
    isboard: {
      type: Boolean
    },
    chartTitle: {
      type: String
    },
    dateStr: {
      type: String
    },
    // 横轴数据
    xData: {
      type: Array
    },
    // 纵轴数据
    chartData: {
      type: Array
    },
    // 画布宽度
    setwidth: {
      type: Number,
      default: 0
    },
    // 画布高度
    setheight: {
      type: Number,
      default: 704
    },
    // 是否显示时间工具
    timepicker: {
      type: Boolean,
      default: false
    },
    // 是否显示工具栏
    toolbox: {
      type: Boolean,
      default: false
    },
    // 提示窗口的标题
    tipName: {
      type: String
    },
    // 图表类型 line/bar/hbar
    type: {
      type: String,
      default: "line"
    },
    // 时间工具栏的类型
    pickerType: {
      type: String,
      default: "daterange"
    },
    // 柱状图x轴数据是否倾斜展示
    xAxisRotate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      chartType: this.type,
      echartsBox: null,
      chartBox: null,
      date: [new Date().setDate(new Date().getDate() - 10), new Date()],
      weekDate: new Date()
    };
  },
  mounted() {
    this.width = this.setwidth;
    this.height = this.setheight;
    this.initCanvasBox();
    window.addEventListener("resize", this.$_handleResizeChart);
    // 组件销毁时，销毁监听事件
    // 在Vue组件中，可以用过$on,$once去监听所有的生命周期钩子函数，如监听组件的updated钩子函数可以写成 this.$on('hook:updated', () => {})
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.$_handleResizeChart);
    });
  },
  activated() {
    if (this.setwidth == 0) {
      this.getWidthAndHeight();
    }
    this.echartsBox.resize();
  },
  methods: {
    $_handleResizeChart() {
      if (this.setwidth == 0) {
        this.getWidthAndHeight();
      }
      // 获取页面大小改变后容器的宽高
      // this.getWidthAndHeight();
      // 调用echarts实例的重绘函数
      this.echartsBox.resize();
    },
    // 初始化echarts容器
    initCanvasBox() {
      // 如果已经存在容器 则移除
      if (this.echartsBox) {
        this.echartsBox.dispose();
      }
      this.chartBox = this.$refs["canvas_box"];
      // 设置画布宽高
      if (this.width == 0) {
        this.getWidthAndHeight();
      }
      this.chartBox.style.width = this.width + "px";
      this.chartBox.style.height = this.height + "px";
      this.echartsBox = echarts.init(this.chartBox);
      if (this.chartType === "line") {
        drawnLine(this.echartsBox, {
          xAxisData: this.xData,
          seriesData: this.chartData,
          seriesName: this.tipName
        });
      } else if (this.chartType === "bar") {
        drawnBar(this.echartsBox, {
          xAxisData: this.xData,
          seriesData: this.chartData,
          seriesName: this.tipName,
          xAxisRotate: this.xAxisRotate
        });
      } else {
        drawnHBar(this.echartsBox, {
          xAxisData: this.xData,
          seriesData: this.chartData,
          seriesName: this.tipName
        });
      }
    },
    // 获得画布宽高
    getWidthAndHeight() {
      this.width = this.chartBox.parentNode.offsetWidth;
      this.chartBox.style.width = this.width + "px";
      this.chartBox.style.height = this.height + "px";
    },
    checkChartType(type) {
      this.chartType = type;
      this.$emit("changeType", type);
    },
    // 下载图片功能
    downLoadHandle() {
      let content = this.echartsBox.getDataURL();
      let aLink = document.createElement("a");
      let blob = base64ToBlob(content);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true);
      aLink.download = "data.png";
      aLink.href = URL.createObjectURL(blob);
      aLink.dispatchEvent(
        new MouseEvent("click", {
          bubbles: true,
          cancelable: true,
          view: window
        })
      );
    },
    timeChange() {
      if (!this.date || !this.weekDate) {
        return;
      }
      if (this.pickerType == "week") {
        return this.$emit("reset-time", this.weekDate);
      }
      this.$emit("reset-time", this.date);
    }
  },
  watch: {
    xData: function(newvalue) {
      this.initCanvasBox();
    },
    type: function(newvalue) {
      this.chartType = newvalue;
    },
    chartType: function() {
      this.initCanvasBox();
    }
  }
};
</script>

<style lang="less" scoped>
.chartarea {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
}
.canvas_box {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.06);
  border-radius: 10px;
}
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding: 0 20px;
  position: relative;
  top: 20px;
  h1 {
    padding: 0;
    margin: 0;
    color: #666666;
  }
}
.tools {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .toolbox {
    font-size: 14px;
    display: flex;
    align-items: center;
    .download {
      color: #1b7befff;
      font-weight: 600;
      margin-right: 30px;
      cursor: pointer;
    }
    .chart_type {
      display: flex;
      align-items: center;
      span {
        margin-right: 20px;
      }
      .type_box {
        border-radius: 4px;
        border: 1px solid #d0d0d0;
        display: flex;
        justify-content: center;
        i:nth-child(3) {
          border: 0;
        }
        i {
          display: block;
          border-right: 1px solid #d0d0d0;
          box-sizing: border-box;
          width: 52px;
          height: 36px;
          color: #c1c1c1;
          font-size: 26px;
          padding-left: 13px;
          padding-top: 5px;
        }
        .active {
          color: #fff;
          background-color: #1b7bef;
        }
      }
    }
  }
}
</style>